#!/bin/sh

# Slackware build script for z26v3

# Written by B. Watson (yalhcru@gmail.com)

# Licensed under the WTFPL. See http://www.wtfpl.net/txt/copying/ for details.

# Possibly TODO: write a man page. Upstream didn't bother to document
# the command line options (even went so far as to remove the man page
# and usage message that used to be in z26 2.x). The options have changed
# since 2.x, so it would be a tedious process of reading the source code.
# Not in the mood right now, maybe later.

# Also possibly TODO: a patch to keep the config files (z26.gui and
# z26.cli) in the user's home directory instead of whatever dir the
# ROM file happens to live in. Leaving it as-is has its uses: different
# sets of ROMs might require different options, so you could separate
# them into dirs and each dir gets its own config file. Maybe the patch
# should leave the config file locations alone, but allow the emulator
# to start in the absence of a config file. Still thinking on this one.

PRGNAM=z26v3
VERSION=${VERSION:-3.02.01}
BUILD=${BUILD:-1}
TAG=${TAG:-_SBo}

if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) ARCH=i586 ;;
    arm*) ARCH=arm ;;
       *) ARCH=$( uname -m ) ;;
  esac
fi

CWD=$(pwd)
TMP=${TMP:-/tmp/SBo}
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

if [ "$ARCH" = "i586" ]; then
  SLKCFLAGS="-O2 -march=i586 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2 -march=i686 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fPIC"
  LIBDIRSUFFIX="64"
else
  SLKCFLAGS="-O2"
  LIBDIRSUFFIX=""
fi

set -e

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $PRGNAM-$VERSION
mkdir -p $PRGNAM-$VERSION
cd $PRGNAM-$VERSION
unzip $CWD/z26v${VERSION}s.zip
chown -R root:root .
find -L .  -perm /111 -a \! -perm 755 -a -exec chmod 755 {} \+ -o \
        \! -perm /111 -a \! -perm 644 -a -exec chmod 644 {} \+

# Fix segfault on exit, when a ROM filename is passed on the command
# line. Please don't gunzip the patch: it has CRLF line endings, git
# will "helpfully" remove them, and the patch will fail.
zcat $CWD/fixsegfault.diff.gz | patch -p1

cd src
make linux CFLAGS="$SLKCFLAGS"
mkdir -p $PKG/usr/games
install -s -m0755 -oroot -groot z26 $PKG/usr/games/$PRGNAM

# .desktop file written by SlackBuild author.
mkdir -p $PKG/usr/share/applications $PKG/usr/share/pixmaps
cat $CWD/$PRGNAM.desktop > $PKG/usr/share/applications/$PRGNAM.desktop
cat z26_icon.png > $PKG/usr/share/pixmaps/$PRGNAM.png

mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
for i in doc/*; do
  sed 's,\r,,' $i > $PKG/usr/doc/$PRGNAM-$VERSION/$( basename $i )
done
cat $CWD/$PRGNAM.SlackBuild > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
cat $CWD/doinst.sh > $PKG/install/doinst.sh

cd $PKG
/sbin/makepkg -l y -c n $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.${PKGTYPE:-tgz}
